package com.zb.validation;

import cn.hutool.core.collection.CollectionUtil;
import com.zb.annotation.ListPattern;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * List校验类
 * @Author WEN
 * @Date 2024/2/4 0004
 **/
public class ListValidator implements ConstraintValidator<ListPattern, List> {
    private boolean required;

    private String[] regexp;
    @Override
    public void initialize(ListPattern constraintAnnotation) {
        this.required = constraintAnnotation.required();
        this.regexp = constraintAnnotation.regexp();
    }

    @Override
    public boolean isValid(List o, ConstraintValidatorContext constraintValidatorContext) {
        if (!this.required && CollectionUtil.isEmpty(o)) {
            return true;
        }
        List result = new ArrayList<>();
        for (Object o1 : o) {
            if (o1 instanceof String) {
                if (Arrays.stream(this.regexp).noneMatch(reg -> Objects.equals(reg, o1))) {
                    result.add(o1);
                }
            }
        }
        return CollectionUtil.isEmpty(result);
    }
}
